<!DOCTYPE html>
<html lang="en" xmlns:sa="http://www.thymeleaf.org/extras/sa-token"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>定时任务管理</title>
    <!--公共模块-->
    <div th:replace="~{layout}"></div>
</head>
<body>
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-header">
            <h3>定时任务管理</h3>
        </div>
        <div class="layui-card-body">
            <!-- 搜索区域 -->
            <form class="layui-form layui-form-pane" lay-filter="searchForm">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">任务名称</label>
                        <div class="layui-input-inline">
                            <input type="text" name="taskName" placeholder="请输入任务名称" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">状态</label>
                        <div class="layui-input-inline">
                            <select name="status">
                                <option value="">全部</option>
                                <option value="1">启用</option>
                                <option value="0">禁用</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button class="layui-btn" lay-submit lay-filter="search">
                            <i class="layui-icon layui-icon-search"></i> 搜索
                        </button>
                        <button type="reset" class="layui-btn layui-btn-primary" lay-filter="searchForm">重置</button>
                    </div>
                </div>
            </form>

            <!-- 操作按钮区域 -->
            <div class="layui-form-item">
                <button class="layui-btn" id="addTaskBtn">
                    <i class="layui-icon layui-icon-add-1"></i> 新增任务
                </button>
                <button class="layui-btn layui-btn-normal" id="taskLogBtn">
                    <i class="layui-icon layui-icon-log"></i> 定时日志
                </button>
                <button class="layui-btn layui-btn-warm" id="batchEnableBtn">
                    <i class="layui-icon layui-icon-play"></i> 批量启用
                </button>
                <button class="layui-btn layui-btn-primary" id="batchDisableBtn">
                    <i class="layui-icon layui-icon-pause"></i> 批量禁用
                </button>
            </div>

            <!-- 数据表格 -->
            <table id="dataTable" lay-filter="dataTable"></table>
        </div>
    </div>
</div>

<!-- 操作列模板 -->
<script type="text/html" id="operationTpl">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="viewLog">查看日志</a>
    {{# if(d.status == 1) { }}
    <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="disable">禁用</a>
    {{# } else { }}
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="enable">启用</a>
    {{# } }}
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>
</script>

<!-- 状态列模板 -->
<script type="text/html" id="statusTpl">
    {{# if(d.status == 1) { }}
    <span style="color: #5FB878;">启用</span>
    {{# } else { }}
    <span style="color: #FF5722;">禁用</span>
    {{# } }}
</script>

<!-- 新增/编辑表单模板 -->
<div class="operation_scheduled_task" style="display: none;">
    <form class="layui-form layui-form-pane" lay-filter="submitForm" style="padding: 20px;">
        <input type="hidden" name="id">
        <div class="layui-form-item">
            <label class="layui-form-label">任务名称</label>
            <div class="layui-input-block">
                <input type="text" name="taskName" placeholder="请输入任务名称" autocomplete="off" class="layui-input" lay-verify="required">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">执行间隔(秒)</label>
            <div class="layui-input-block">
                <input type="number" name="intervalSeconds" placeholder="请输入执行间隔" autocomplete="off" class="layui-input" lay-verify="required|number">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">调用目标</label>
            <div class="layui-input-block">
                <textarea name="targetString" placeholder="请输入调用目标字符串" class="layui-textarea" lay-verify="required"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">状态</label>
            <div class="layui-input-block">
                <input type="checkbox" name="status" lay-skin="primary" title="启用" value="1">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="submitForm">提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</div>



<script th:inline="none">
    layui.use(['table', 'form', 'layer', 'laydate'], function(){
        var table = layui.table;
        var form = layui.form;
        var layer = layui.layer;
        var laydate = layui.laydate;

        // 初始化表格
        var tableIns = table.render({
            elem: '#dataTable',
            url: '/manager/scheduledTask/listByPage',
            method: 'post',
            contentType: 'application/json',
            page: true,
            limit: 20,
            cols: [[
                {type: 'checkbox', fixed: 'left'},
                {field: 'id', title: 'ID', width: 80, sort: true},
                {field: 'taskName', title: '任务名称', width: 150},
                {field: 'intervalSeconds', title: '执行间隔(秒)', width: 120},
                {field: 'targetString', title: '调用目标', width: 300},
                {field: 'status', title: '状态', width: 100, templet: '#statusTpl'},
                {field: 'createTime', title: '创建时间', width: 180},
                {field: 'updateTime', title: '更新时间', width: 180},
                {title: '操作', width: 300, templet: '#operationTpl', fixed: 'right'}
            ]],
            parseData: function(res){
                console.log('表格解析数据:', res);
                var result = {
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.data ? res.data.total : 0,
                    "data": res.data ? res.data.records : []
                };
                console.log('解析结果:', result);
                return result;
            },
            done: function(res, curr, count) {
                console.log('表格加载完成:', res);
                console.log('当前页:', curr);
                console.log('总条数:', count);
                
                // 如果是第一页且数据加载成功，清空搜索表单
                if(curr === 1 && res && res.data && res.data.records && res.data.records.length > 0) {
                    setTimeout(function(){
                        console.log('开始清空搜索表单');
                        // 清空搜索表单
                        var searchForm = $('form[lay-filter="searchForm"]')[0];
                        if(searchForm) {
                            searchForm.reset();
                            // 重新渲染表单
                            form.render();
                            console.log('搜索表单已清空');
                        } else {
                            console.log('未找到搜索表单');
                        }
                    }, 300);
                }
            }
        });

        // 搜索功能
        form.on('submit(search)', function(data){
            console.log('搜索按钮被点击，搜索条件:', data.field);
            tableIns.reload({
                where: data.field,
                page: {curr: 1}
            });
            
            return false;
        });

        // 重置按钮事件
        form.on('reset(searchForm)', function(data){
            console.log('重置按钮被点击');
            // 清空表单
            var searchForm = $('form[lay-filter="searchForm"]')[0];
            if(searchForm) {
                searchForm.reset();
                form.render();
            }
            // 重新加载表格
            setTimeout(function(){
                tableIns.reload({
                    where: {},
                    page: {curr: 1}
                });
            }, 100);
        });

        // 为主页面重置按钮添加点击事件监听器
        $('button[type="reset"]').on('click', function(){
            console.log('重置按钮被点击');
            setTimeout(function(){
                // 清空表单
                var searchForm = $('form[lay-filter="searchForm"]')[0];
                if(searchForm) {
                    searchForm.reset();
                    form.render();
                }
                // 重新加载表格
                tableIns.reload({
                    where: {},
                    page: {curr: 1}
                });
            }, 100);
        });

        // 新增任务按钮
        $('#addTaskBtn').on('click', function(){
            showFormDialog();
        });

        // 定时日志按钮点击事件
        $('#taskLogBtn').on('click', function(){
            // 在当前页面跳转到日志页面
            window.location.href = '/manager/scheduledtask/log';
        });

        // 批量启用按钮
        $('#batchEnableBtn').on('click', function(){
            var checkStatus = table.checkStatus('dataTable');
            var data = checkStatus.data;
            if(data.length === 0){
                layer.msg('请选择要启用的任务');
                return;
            }
            var ids = data.map(function(item){ return item.id; });
            batchUpdateStatus(ids, 1);
        });

        // 批量禁用按钮
        $('#batchDisableBtn').on('click', function(){
            var checkStatus = table.checkStatus('dataTable');
            var data = checkStatus.data;
            if(data.length === 0){
                layer.msg('请选择要禁用的任务');
                return;
            }
            var ids = data.map(function(item){ return item.id; });
            batchUpdateStatus(ids, 0);
        });

        // 表格行工具事件
        table.on('tool(dataTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'edit'){
                showFormDialog(data);
            } else if(obj.event === 'enable'){
                updateTaskStatus(data.id, 1);
            } else if(obj.event === 'disable'){
                updateTaskStatus(data.id, 0);
            } else if(obj.event === 'delete'){
                layer.confirm('确定要删除这个任务吗？', function(index){
                    deleteTask(data.id);
                    layer.close(index);
                });
            } else if(obj.event === 'viewLog'){
                // 在当前页面跳转到日志页面，并传递任务名称参数
                window.location.href = '/manager/scheduledtask/log?taskName=' + encodeURIComponent(data.taskName);
            }
        });

        // 显示表单对话框
        function showFormDialog(data){
            var title = data ? '编辑定时任务' : '新增定时任务';
            var content = $('.operation_scheduled_task').html();
            
            layer.open({
                type: 1,
                title: title,
                area: ['900px', '500px'],
                content: content,
                success: function(layero, index){
                    // 重新渲染表单
                    form.render();
                    
                    if(data){
                        // 手动设置表单字段值
                        setTimeout(function(){
                            // 设置任务ID（编辑时需要）
                            layero.find('input[name="id"]').val(data.id);
                            // 设置任务名称
                            layero.find('input[name="taskName"]').val(data.taskName);
                            // 设置执行间隔
                            layero.find('input[name="intervalSeconds"]').val(data.intervalSeconds);
                            // 设置调用目标字符串
                            layero.find('textarea[name="targetString"]').val(data.targetString);
                            // 设置状态
                            if(data.status == 1){
                                layero.find('input[name="status"]').prop('checked', true);
                            } else {
                                layero.find('input[name="status"]').prop('checked', false);
                            }
                            // 重新渲染表单
                            form.render();
                        }, 100);
                    }
                    
                    // 表单提交
                    form.on('submit(submitForm)', function(formData){
                        submitForm(formData.field, data ? 'update' : 'add');
                        return false;
                    });
                }
            });
        }

        // 提交表单
        function submitForm(data, type){
            var url = type === 'update' ? '/manager/scheduledTask/update' : '/manager/scheduledTask/add';
            
            // 处理状态字段 - checkbox选中时为1，未选中时为0
            if(data.status === '1' || data.status === true || data.status === 1){
                data.status = 1;
            } else {
                data.status = 0;
            }
            
            CoreUtil.sendPost(url, data, function(res){
                layer.msg('操作成功');
                layer.closeAll();
                tableIns.reload();
            });
        }

        // 删除任务
        function deleteTask(id){
            CoreUtil.sendDelete('/manager/scheduledTask/delete/' + id, null, function(res){
                layer.msg('删除成功');
                tableIns.reload();
            });
        }

        // 更新任务状态
        function updateTaskStatus(id, status){
            var url = status === 1 ? '/manager/scheduledTask/status/enable/' : '/manager/scheduledTask/status/disable/';
            CoreUtil.sendPost(url + id, null, function(res){
                layer.msg(status === 1 ? '启用成功' : '禁用成功');
                tableIns.reload();
            });
        }

        // 批量更新状态
        function batchUpdateStatus(ids, status){
            CoreUtil.sendPost('/manager/scheduledTask/status/batchUpdateStatus', {
                ids: ids,
                status: status
            }, function(res){
                layer.msg(status === 1 ? '批量启用成功' : '批量禁用成功');
                tableIns.reload();
            });
        }



    });
</script>

</body>
</html>
